#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import random
import string  # python自带的字符串模块

from django.core.mail import send_mail
import smtplib, datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from users.models import EmailVerification
from online.settings import EMAIL_FROM  # 引入自定义的配置



def send_link_email(email, send_type='register'):
    """发送邮件，内容为验证链接"""
    emailinfo = EmailVerification()
    emailinfo.email = email
    emailinfo.send_type = send_type
    emailinfo.code = send_code_email()
    if send_type == 'register':
        email_subject = '在线学习网激活邮件（请勿回复）'
        email_message = '欢迎您注册在线学习网账号，请点击下面的链接完成激活:\nhttp://192.168.69.33:80/users/active/' + emailinfo.code
        send_mail(email_subject, email_message, EMAIL_FROM, [email])
        emailinfo.save()
        # sendemail('传智在线学习网修改邮箱邮件(请勿回复)', '欢迎您注册在线学习网账号，请点击下面的链接完成激活:\nhttp://127.0.0.1:8000/users/active/' + emailinfo.code,email)
        emailinfo.save()
    elif send_type == 'forget':
        email_subject = '在线学习网密码重置邮件（请勿回复）'
        email_message = '欢迎您使用在线学习网平台，请点击下面的链接重置登录密码:\nhttp://192.168.69.33:80/users/pwdreset/' + emailinfo.code
        send_mail(email_subject, email_message, EMAIL_FROM, [email])
        emailinfo.save()
    elif send_type == 'yzm':
        email_subject = '在线学习网修改邮箱邮件（请勿回复）'
        email_message = '欢迎您使用在线学习网平台,您正在修改邮箱,验证码5分钟内有效,请尽快完成验,如非本人操作,请忽略,验证码为:' + emailinfo.code
        send_mail(email_subject, email_message, EMAIL_FROM, [email])
        emailinfo.save()
    elif send_type == 'update_email':
        pass

def send_code_email(link_code_length=16):
    """生成随机邮箱验证码，作为验证链接的一部分"""
    link_code = ''
    chars = string.ascii_letters + str(string.digits)
    chars_length = len(chars)
    for i in range(link_code_length-1):
        link_code += chars[random.randint(0, chars_length-1)]
    return link_code


def sendemail(subject, maintext,email):
    emailinfo = EmailVerification()
    emailinfo.email = email
    user = 'lomo9820@163.com'
    pwd = 'lomo9820'
    to = [email]
    msg = MIMEMultipart()
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = Header(user)

    content1 = MIMEText(maintext, 'plain', 'utf-8')
    msg.attach(content1)

    s = smtplib.SMTP('smtp.163.com')

    try:
        s.set_debuglevel(1)              #调试使用
        s.starttls()                     #建议使用
        s.login(user, pwd)
        s.sendmail(user, to, msg.as_string())
        s.close()
    except BaseException as e:
        e = str(e)
        with open('send_email_error ' + str(datetime.datetime.now()) + '.txt', 'w+') as fa:
            fa.write(e)